<?php

class AppController extends Controller
{
	public $layout='intro';
	
	public function actionIndex()
	{
		// the download link is http://yamii.fi/?qr=anything&email=1(用于统计从那些二维码扫描进来的)
		$qr = Yii::app()->request->getQuery('qr');
		if (!empty($qr)) {
			//email
			$IsEmail = Yii::app()->request->getQuery('email');
			if ($IsEmail) {
				$email = base64_decode($qr);
				BUtils::Logging('email_download', array($email, $_GET));
			}
			
			//check the client type
			$detect = new Mobile_Detect();
			if ($detect->isIOS()){
				$deviceType = 'iphone';
				$url = Yii::app()->createUrl('app/mobile', array('download'=>1, 'type'=>'iphone', 'qr'=>$qr));
				//$url = Yii::app()->createUrl('/mobile/default/index', array('utm_source'=>$deviceType, 'utm_medium'=>$qr));
				Yii::app()->request->redirect($url, true);
			} elseif ($detect->isAndroidOS()) {
				$deviceType = 'android';
				$url = Yii::app()->createUrl('app/mobile', array('download'=>1, 'type'=>'android', 'qr'=>$qr));
				//$url = Yii::app()->createUrl('/mobile/default/index', array('utm_source'=>$deviceType, 'utm_medium'=>$qr));
				Yii::app()->request->redirect($url, true);
			} elseif ($detect->isWindowsPhoneOS()) {
				$url = Yii::app()->createUrl('/mobile/default/index', array('utm_source'=>$deviceType, 'utm_medium'=>$qr));
				Yii::app()->request->redirect($url, true);
			}
		}
		
		$this->render('index');
	}
	
	public function actionAbout()
	{
		if (strtolower(Yii::app()->language) == 'en_gb')
			$this->render('about');
		else {
			Yii::app()->language = 'fi_fi';
			$this->render('about_fi');
		}
	}

	public function actionFaq()
	{
		if (strtolower(Yii::app()->language) == 'en_gb')
			$this->render('faq');
		else {
			Yii::app()->language = 'fi_fi';
			$this->render('faq_fi');
		}
	}

	public function actionPrivacy()
	{
		$this->render('privacy');
	}

	public function actionTerms()
	{
		$this->render('terms');
	}

	public function actionJobs()
	{
		$this->render('jobs');
	}
	
	public function actionMobile()
	{
		$download = Yii::app()->request->getParam('download');
		if (!empty($download)) {
			$type = Yii::app()->request->getParam('type');
			if ($type == 'iphone') {
				$url = 'https://itunes.apple.com/us/app/yamii/id594294678';
				Yii::app()->request->redirect($url, false);
			} elseif ($type == 'android') {
				$url = 'https://play.google.com/store/apps/details?id=com.yamii.android';
				Yii::app()->request->redirect($url, false);
			}
		}
		
		$this->render('mobile');
		
		$data = $_GET;
		$data['agent'] = Yii::app()->request->getUserAgent();
		BUtils::Logging('download', $data);
		
		//save to DB
		if (!empty($download)) {
			$this->_storeDownloadRef($type, Yii::app()->request->getUrl(), Yii::app()->request->getUrlReferrer());
		}
	}
	
	public function actionWindows() {
		$subscribe = Yii::app()->request->getParam('subscribe');
		if (empty($subscribe)) {
			if (Yii::app()->request->isAjaxRequest) {
				$this->renderPartial('windows');
			} else {
				$this->render('windows');
			}
		} else {
			$email = Yii::app()->request->getPost('txt_email');
			if (empty($email)) {
				$this->_sendJSON(500, BUtils::T('email_enter_empty_error_msg'));
			} else {
				$validator = new CEmailValidator();
				if (!$validator->validateValue($email)){
					$this->_sendJSON(500, BUtils::T('email_address_error_msg'));
				}
			}
			
			//save to DB: tbl_app_subscribe
			$sql_subscribe = 'INSERT INTO tbl_app_subscribe (device_type, email, ip_address, agent, lang) VALUES (:device_type, :email, :ip_address, :agent, :lang)';
			$params = array(
				':device_type' => 'windows',
				':email' => $email,
				':ip_address' => Yii::app()->request->getUserHostAddress(),
				':agent' => Yii::app()->request->getUserAgent(),
				':lang' => BUtils::T('LNG'),
			);
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_subscribe);
			$command->execute($params);
			$connection->active = false;
			
			//success
			$this->_sendJSON(200, BUtils::T('subscribe_windows_app_done_msg', array('{email}' => $email)));
		}
	}
	
	public function actionCampaign() {
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('_campaign');
		} else {
			//query merchant list who has offer published on that day
			$sql_merchants = 'SELECT m.id, m.name, m.address, m.city, m.url_logo, m.url_offer_img, COUNT(s.id) AS specials
				FROM tbl_merchant_account m
				LEFT JOIN tbl_merchant_special s ON s.id_merchant=m.id AND s.trash=0 AND s.status=1 AND 
					s.start_date<NOW() AND s.end_date>:start_date
				WHERE m.status<99 and m.password is not null AND m.name is not null and m.latitude is not null and m.longitude is not null
				  AND m.city=:city
				GROUP BY m.id
				HAVING specials>0
				ORDER BY m.name ASC';
			//query the users who has redeemed offers
			$sql_users = 'SELECT DISTINCT u.id, u.name, u.picture, s.id_merchant, r.redeemed_time
				FROM tbl_merchant_special_redeem r
				INNER JOIN tbl_user_account u ON u.id=r.id_user
				INNER JOIN tbl_merchant_special s ON s.id=r.id_special
				WHERE r.redeemed=2 AND r.redeemed_time BETWEEN :start_date AND :end_date
				ORDER BY r.redeemed_time DESC ';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_merchants);
			$merchants = $command->queryAll(true, array(
				':start_date' => '2013-04-12',
				':city' => 'helsinki',
			));
			
			$command = $connection->createCommand($sql_users);
			$users = $command->queryAll(true, array(
				':start_date' => '2013-04-12',
				':end_date' => '2013-04-30',
			));
			$connection->active = false;
			
			//filter the users who redeemed offer more times
			$uni_users = array();
			foreach ($users as $u) {
				$uni_users[$u['id']] = $u;
			}
			
			$rows = array();
			foreach ($merchants as $m) {
				$row = $m;
				
				//check users
				$row['users'] = array();
				foreach ($uni_users as $u) {
					if ($u['id_merchant'] == $m['id']) {
						$row['users'][] = $u;
					}
				}
				$rows[] = $row;
			}
			$this->render('campaign', array('rows' => $rows));
		}
	}
	
	public function actionSubscribe() {
		$data = $_POST;
		$data['agent'] = Yii::app()->request->getUserAgent();
		BUtils::Logging('subscribe', $data);
		
		$email = Yii::app()->request->getPost('txt_email');
		if (empty($email)) {
			$this->_sendJSON(500, BUtils::T('email_enter_empty_error_msg'));
		} else {
			$validator = new CEmailValidator();
			if (!$validator->validateValue($email)){
				$this->_sendJSON(500, BUtils::T('email_address_error_msg'));
			}
		}
		
		//success
		$this->_sendJSON(200, BUtils::T('yamii_download_success_msg'), false);
		
		//save to DB and send email with download link (with the tracker)
		//make a html email
		if (Yii::app()->language == 'fi_fi') {
			$subject = 'Yamii - Tarjoustutkasi!';
			$htmlText = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body>
<p>Hei</p>
<p>Hienoa, että olet löytänyt meidät: Yamii - Tarjoustutkasi!</p>
<p>Klikkaa latauslinki alla ladataksesi Yamii sovellus älypuhelimellasi!<br /><a href="http://yamii.fi/?qr={email_address}&email=1">http://yamii.fi/?qr={email_address}</a></p>
<p>Kiitos, että valitset meidät. Teemme älypuhelimesi tarjoustutkaksi!</p>
<p>Ystävällisin terveisin<br />Yamii Tiimi</p>
</body>
</html>
HTML;
			$plainText = <<<TEXT
Hei

Hienoa, että olet löytänyt meidät: Yamii – Tarjoustutkasi!

Klikkaa latauslinki alla ladataksesi Yamii sovellus älypuhelimellasi!
http://yamii.fi/?qr={email_address}&email=1

Kiitos, että valitset meidät. Teemme älypuhelimesi tarjoustutkaksi!

Ystävällisin terveisin
Yamii Tiimi
TEXT;
		} else {
			$subject = 'Yamii - Your Deal Radar!';
			$htmlText = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body>
<p>Hi,</p>
<p>It's great that you found us: Yamii - Your Deal Radar!</p>
<p>Please click the following link to download Yamii app with your smart-phone.<br /><a href="http://yamii.fi/?qr={email_address}&email=1">http://yamii.fi/?qr={email_address}</a></p>
<p>Thank you very much for choosing us. Let's make your smart-phone a deal radar!</p>
<p>Best regards,<br />Yamii Team</p>
</body>
</html>
HTML;
			$plainText = <<<TEXT
Hi,

It's great that you found us: Yamii - Your Deal Radar!

Please click the following link to download Yamii app with your smart-phone.
http://yamii.fi/?qr={email_address}&email=1

Thank you very much for choosing us. Let's make your smart-phone a deal radar!

Best regards,
Yamii Team
TEXT;
		}
		
		$receivers = array(
			$email
		);
		$htmlText = str_replace('{email_address}', base64_encode($email), $htmlText);
		$plainText = str_replace('{email_address}', base64_encode($email), $plainText);
		
		BUtils::SendEmailOut($subject, $receivers, $htmlText, $plainText);
	}
}